package com.example.myapplication.untils;

import android.annotation.SuppressLint;
import android.util.Log;

import com.google.gson.Gson;

import org.apache.http.conn.ssl.AllowAllHostnameVerifier;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

import cn.hutool.core.util.StrUtil;
import okhttp3.*;

public class HttpUtils {

    private static final String TAG = "TAG";
    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");


    final OkHttpClient client
            = new OkHttpClient.Builder()
            .connectTimeout(10, TimeUnit.SECONDS)
            .writeTimeout(10, TimeUnit.SECONDS)
            .readTimeout(20, TimeUnit.SECONDS)
            .build();

    public String postJson(String url, Map<String, String> map_header, HashMap<String, String> map) throws IOException {

        Headers.Builder builder_header = new Headers.Builder();
        for (String key : map_header.keySet()) {//通过keySet()方法得到key的值，然后获取value
            builder_header.add(key, Objects.requireNonNull(map_header.get(key)));
        }
        Headers headers = builder_header.build();

        Gson gson = new Gson();
        String json = gson.toJson(map);
        RequestBody body = RequestBody.create(JSON, json);
        Request request = new Request.Builder()
                .url(url)
                .headers(headers)
                .post(body)
                .build();

        try (Response response = client.newCall(request).execute()) {
            ResponseBody responseBody = response.body();
            if (Objects.isNull(responseBody)) {
                throw new RuntimeException("响应体为空");
            }
            return responseBody.string();
        } catch (Exception e) {
            System.out.println("postJson: "+e);

            Log.e("TAG", "postJson: ",e );

            return "";
        }
    }





    public String postJson(String url, String json) {
        if (StrUtil.isEmpty(json) || StrUtil.isEmpty(url)) {
            throw new RuntimeException("url或请求参数不能为空");
        }

        RequestBody body = RequestBody.create(JSON, json);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();

        try (Response response = client.newCall(request).execute()) {
            ResponseBody responseBody = response.body();
            if (Objects.isNull(responseBody)) {
                throw new RuntimeException("响应体为空");
            }
            return responseBody.string();
        } catch (Exception e) {
            Log.e(TAG, "postJson: ",e );
            return "";
        }
    }

    /**
     * @param url
     * @param queryParamMap
     * @return
     */
    public String get(String url, Map<String, String> map_header, HashMap<String, String> queryParamMap) throws IOException {

        if (StrUtil.isEmpty(url)) {
            throw new RuntimeException("url或请求参数不能为空");
        }
        Headers.Builder builder_header = new Headers.Builder();
        for (String key : map_header.keySet()) {//通过keySet()方法得到key的值，然后获取value
            builder_header.add(key, Objects.requireNonNull(map_header.get(key)));
        }
        Headers headers = builder_header.build();


        HttpUrl.Builder builder = Objects.requireNonNull(HttpUrl.parse(url)).newBuilder();
        if (queryParamMap != null && queryParamMap.size() != 0) {
            queryParamMap.forEach(builder::addQueryParameter);
        }
        url = builder.build().toString();

        Request request = new Request.Builder()
                .url(url)
                .headers(headers)
                .build();
        try (Response response = client.newCall(request).execute()) {
            ResponseBody responseBody = response.body();
            if (Objects.isNull(responseBody)) {
                throw new RuntimeException("响应体为空");
            }
            return responseBody.string();
        } catch (Exception e) {
            Log.e(TAG, "get: ",e);
            return "";
        }
    }


    public String get(String url) throws IOException {

        if (StrUtil.isEmpty(url)) {
            throw new RuntimeException("url或请求参数不能为空");
        }

        HttpUrl.Builder builder = Objects.requireNonNull(HttpUrl.parse(url)).newBuilder();

        url = builder.build().toString();

        Request request = new Request.Builder()
                .url(url)
                .build();
        try (Response response = client.newCall(request).execute()) {
            ResponseBody responseBody = response.body();
            if (Objects.isNull(responseBody)) {
                throw new RuntimeException("响应体为空");
            }
            return responseBody.string();
        } catch (Exception e) {
            Log.e(TAG, "get: ",e);
            return "";
        }
    }


}